import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_nodes_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/closure/closure_appointment_entity.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

class CommonApprovalListController extends GetxController {
  /// todo 封闭化预约流程-流程唯一编码 目前写死
  final String processEncoding = 'hy_Tc3YUScs';

  /// 搜索使用key
  GlobalKey<CustomEasyRefreshListState>? globalKey;

  /// 当前执行节点
  ProcessNodesEntity implementNode = ProcessNodesEntity();

  /// 下一个执行节点
  ProcessNodesEntity nextNode = ProcessNodesEntity();

  /// 是否为结束节点的前一个节点
  bool last = false;

  /// 人员开始时间
  String personnelStartTime = '';

  /// 普通车辆开始时间
  String vehicleStartTime = '';

  /// 危化车辆开始时间
  String dangerousStartTime = '';

  /// 人员结束时间
  String personnelEndTime = '';

  /// 普通车辆结束时间
  String vehicleEndTime = '';

  /// 危化车辆结束时间
  String dangerousEndTime = '';

  /// 初始化数据
  void initData(GlobalKey<CustomEasyRefreshListState> globalKey) {
    this.globalKey = globalKey;
  }

  /// 获取列表数据
  Future<List<ClosureAppointmentEntity>> getListData(int pageNum, int pageSize, {String? search, int? type}) async {
    final Map<String, dynamic> queryParameters = {};
    queryParameters['pageNum'] = pageNum;
    queryParameters['pageSize'] = pageSize;
    queryParameters['reservationType'] = type;
    if (type == 0) {
      queryParameters['name'] = search;
    } else {
      queryParameters['licensePlate'] = search;
    }
    // 添加时间筛选
    switch (type) {
      case 0:
        queryParameters['startDate'] = personnelStartTime;
        queryParameters['endDate'] = personnelEndTime;
        break;
      case 1:
        queryParameters['startDate'] = vehicleStartTime;
        queryParameters['endDate'] = vehicleEndTime;
        break;
      case 2:
        queryParameters['startDate'] = dangerousStartTime;
        queryParameters['endDate'] = dangerousEndTime;
        break;
      default:
        break;
    }
    // 获取列表接口
    final res = await HttpUtil()
        .generatePostRequest<List<ClosureAppointmentEntity>>(
          Interface.getAuditList,
          data: queryParameters,
        )
        .execute();
    List<ClosureAppointmentEntity>? data;
    res.onSuccess((result) {
      if (result.data != null) {
        data = result.data!;
      }
    });
    return data ?? [];
  }

  /// 选择时间后刷新列表
  void selectTimePeriod(String startTime, String endTime, int type) {
    switch (type) {
      case 0:
        personnelStartTime = startTime;
        personnelEndTime = endTime;
        break;
      case 1:
        vehicleStartTime = startTime;
        vehicleEndTime = endTime;
        break;
      case 2:
        dangerousStartTime = startTime;
        dangerousEndTime = endTime;
        break;
      default:
        break;
    }
    refreshPage();
    update();
  }

  /// 进入审批详情页面
  Future<void> toApprovalDetailsPage({required int type, required ClosureAppointmentEntity item}) async {
    // 如果状态不为待审批,则进入查看详情页面
    if (item.appointmentStatus != 0) {
      Get.toNamed(AppRoutes.closureApprovalDetails, arguments: {
        'type': type,
        'item': item,
        'last': last,
        'isDetails': true,
      });
      return;
    }

    // 获取数据
    final res = await HttpUtil().generateGetRequest<List<ProcessNodesEntity>>(Interface.getProcessNodesByBusinessId,
        queryParameters: {'processEncoding': processEncoding, 'businessId': item.id}).execute(isShowLoading: true);

    // 查询到流程节点数据
    res.onSuccess((result) async {
      if (result.data!.isNotEmpty) {
        final List<ProcessNodesEntity> nodeList = result.data!;
        for (int i = 0; i < nodeList.length; i++) {
          final node = nodeList[i];
          //找到当前执行节点
          if (node.executableOrNot == 1) {
            // 点击项的执行节点
            implementNode = node;
            try {
              // 是否为结束节点的前一个节点
              last = (i == nodeList.length - 2);
              // 如果不为最后一个节点,设置下一个节点数据
              if (!last) {
                nextNode = nodeList[i + 1];
              }
              // 只有审批节点会显示
              Get.toNamed(AppRoutes.closureApprovalDetails, arguments: {
                'type': type,
                'item': item,
                'last': last,
                'isDetails': false,
              })?.then((value) {
                refreshPage();
              });
              break;
            } catch (e) {
              AppToast.showWarning('当前审批流程节点数据异常!');
              break;
            }
          }
        }
      } else {
        AppToast.showWarning('数据异常,未查询到流程数据!');
      }
    });
  }

  /// 搜索
  void refreshPage() {
    globalKey?.currentState?.onRefresh();
  }
}
